﻿using System;
using System.Linq;
using SydEnergiPrototype.Model;

namespace SydEnergiPrototype.Logic
{
    public class SearchQueryBuilder : ISearchQueryBuilder
    {
        public SearchQuery Build(string searchParameter)
        {
            var splitParameter = DetermineSeparation(searchParameter);

            if (splitParameter.Count() == 1)
            {
                int zipCode;
                if (int.TryParse(splitParameter[0], out zipCode))
                    return new SearchQuery(null, zipCode, null);

                return new SearchQuery(splitParameter[0], 0, null);
            }

            if (splitParameter.Count() == 2)
            {
                int zipCode;
                if (int.TryParse(splitParameter[0], out zipCode))
                    return new SearchQuery(splitParameter[1], zipCode, null);

                if (int.TryParse(splitParameter[1], out zipCode))
                    return new SearchQuery(splitParameter[0], zipCode, null);
                
                return new SearchQuery(splitParameter[0], 0, splitParameter[1]);
            }

            if(splitParameter.Count() == 3)
            {
                int zipCode;
                if (int.TryParse(splitParameter[0], out zipCode))
                    return new SearchQuery(splitParameter[1], zipCode, splitParameter[2]);

                if (int.TryParse(splitParameter[1], out zipCode))
                    return new SearchQuery(splitParameter[0], zipCode, splitParameter[2]);

                if(int.TryParse(splitParameter[2], out zipCode))
                    return new SearchQuery(splitParameter[0], zipCode, splitParameter[1]);
                
                throw new ArgumentException("SearchQuery cannot be built from searchparameter");
            }

            throw new Exception("Error in searchparameter");
        }

        private static string[] DetermineSeparation(string searchParameter)
        {
            return searchParameter.Replace(" ", "").Split(',');
        }
    }
}